package ct.model;

import java.util.Date;
import java.util.GregorianCalendar;

public class DateSimple extends GregorianCalendar {

	private static final long serialVersionUID = 1L;

	// Milliseconds in a day
	public static final long milliInDay = 86400000;

	// Setters and getters
	public int getDay() {
		return this.get(GregorianCalendar.DAY_OF_MONTH);
	}

	public int getMonth() {
		return this.get(GregorianCalendar.MONTH) + 1;
	}

	public int getYear() {
		return this.get(GregorianCalendar.YEAR);
	}

	public String toString() {
		return String.format("%1$te/%1$tm/%1$tY", this);
	}

	// Same constructors as GregorianCalendar by default
	public DateSimple() {
		super();
	}

	public DateSimple(int year, int month, int dayOfMonth) {
		super(year, month - 1, dayOfMonth);
	}

	public DateSimple(Date date) {
		super();
		this.setTime(date);
	}

	// Return true if this date is posterior to the date given in argument in
	// the same year
	protected boolean afterInYear(DateSimple ds) {
		DateSimple temp = new DateSimple(this.getYear(), ds.getMonth(), ds
				.getDay());

		return after(temp);
	}

	// Return the number of complete year between this date and the date given
	// in argument
	// Negative if the date given in argument is anterior to this
	protected int getNbYearTo(DateSimple ds) {
		// If ds date is anterior to this, return the negative contrary value
		if (this.after(ds))
			return -1 * ds.getNbYearTo(this);

		DateSimple temp = new DateSimple(this.getYear(), ds.getMonth(), ds
				.getDay());

		if (!temp.before(this))
			return ds.getYear() - this.getYear();
		else
			return ds.getYear() - this.getYear() - 1;
	}

	// Return the amount of day between this date and the date given in
	// parameter
	protected int getNbDayTo(DateSimple ds) {

		DateSimple temp = new DateSimple(ds.getYear() - this.getNbYearTo(ds),
				ds.getMonth(), ds.getDay());

		return (int) ((temp.getTimeInMillis() - this.getTimeInMillis()) / milliInDay);
	}

	// Return the number of days between this date and the date given in
	// argument
	// Modulo a year (i.e result is in range [0; 366]
	protected int getNbDayToIgnoreYear(DateSimple ds) {
		DateSimple temp;

		if (this.afterInYear(ds))
			temp = new DateSimple(this.getYear() + 1, ds.getMonth(), ds
					.getDay());
		else
			temp = new DateSimple(this.getYear(), ds.getMonth(), ds.getDay());

		return this.getNbDayTo(temp);
	}

}
